<?php
/**
 * DESC: 商品规格
 * 作者:晨光
 * EMAIL:461718846@qq.com
 * DATE:2020-06-02
 */

namespace app\common\model;


use think\Db;
use think\Model;

class GoodsFormat extends Model
{
    /**
     * 生成vantsku格式
     * @param $goods_id
     */
    public static function getVantSku($goods_id){
        $goods = Goods::where('id','=',$goods_id)->find();
        $format = GoodsFormat::where('goods_id','=',$goods_id)->select();
        $res = [];
//        默认价格
        $res['price'] = $goods['price'];
//         商品总库存
        $res['stock_num'] = self::where('goods_id','=',$goods_id)->sum('stock');
        $res['collection_id'] = '';
//         是否无规格商品
        $res['none_sku'] = false;
        $res['hide_stock'] = false;
        $res['messages'] = [];
        $res['tree'] = [];
        $res['list'] = [];
        if (!empty($format)){
//            获取有多少个规格
            $skuDetail = explode(',',$format[0]['sku']);
//            规格名
            $sku = [];
            if (!empty($skuDetail)){
                foreach ($skuDetail as $k=>$v){
                    $s1 = explode(':',$v);
                    $sku[$k]['name_id'] = $s1[0];
                    $sku[$k]['value'][] = $s1[1];
                }
            }
            if (!empty($sku)){
                foreach ($sku as $k1=>$v1){
                    $res['tree'][$k1]['k'] = Db::name('goods_format_name')->where('id','=',$v1['name_id'])->value('name');
                    $res['tree'][$k1]['k_s'] = 's'.($k1+1);
                    foreach ($format as $k2=>$v2){
                        $sku = explode(',',$v2['sku']);
                        foreach ($sku as $ks=>$vs){
                            $vs_sku = explode(':',$vs);
                            if ($vs_sku[0] == $v1['name_id']){
                                $res['tree'][$k1]['v'][] = [
                                    'id'=>$vs_sku[1],
                                    'name'=>Db::name('goods_format_value')->where('id','=',$vs_sku[1])->value('name'),
                                ];
                            }
                        }
//                        array_unique($res['tree'][$k1]['v'], SORT_REGULAR);
                        $res['tree'][$k1]['v'] = assoc_unique($res['tree'][$k1]['v'],'id');
                    }
                }
            }

            foreach ($format as $k3=>$v3){
                $sku = explode(',',$v3['sku']);
                $res['list'][] = [
                    'id'=>$v3['id'],
                    'price'=>$v3['price']*100,
                    's1'=>isset($sku[0])?explode(':',$sku[0])[1]:'',
                    's2'=>isset($sku[1])?explode(':',$sku[1])[1]:'',
                    's3'=>isset($sku[2])?explode(':',$sku[2])[1]:'',
                    'stock_num'=>$v3['stock'],
                ];
            }
        }
        return $res;
    }
}
